<script setup>
import { ref, computed, watch } from 'vue'
import BaseRankingChart from '@/components/chart/BaseRankingChart.vue'
import CustomDateRadio from '@/components/header/CustomDateRadio.vue'
import { useCompanyStore } from '@/stores/company'
import { getAllSubCategoryReportApi } from '@/api/category'
import { handleError } from '@/utils/handleError'

const props = defineProps({
    title: {
        type: String,
        default: '用途用水排名'
    },
    height: {
        type: String,
        default: '230px'
    }
})

const companyStore = useCompanyStore()
const rankingChartTime = ref(null)
const rankingChartData = ref([])
const rankingChartLoading = ref(false)

// 监听公司变化，重新获取数据
watch(() => companyStore.currentCompany, () => {
    if (rankingChartTime.value) {
        getSubCategoryRankingData()
    }
}, { deep: true })

// 获取用途排名数据
async function getSubCategoryRankingData() {
    if (!rankingChartTime.value) return
    console.log(rankingChartTime.value);

    rankingChartLoading.value = true
    try {
        let res = await getAllSubCategoryReportApi({
            id: companyStore.currentCompany.id,
            start_time: rankingChartTime.value.start_time,
            end_time: rankingChartTime.value.end_time,
            type: 1,  // 用水类型
        })

        if (res?.aggregated_data) {
            if (!Array.isArray(res.aggregated_data)) {
                console.warn('排名数据格式不正确, 期望数组但收到:', typeof res.aggregated_data);
                rankingChartData.value = [];
                return;
            }
            console.log(res.aggregated_data);

            rankingChartData.value = res.aggregated_data.flat()
                .map(item => {
                    // 添加项目级别的空值检查
                    if (!item) return null;

                    // 确保usage是数组
                    const usage = Array.isArray(item.usage) ? item.usage : [];

                    return {
                        name: item.subcategory || '其他',
                        value: usage.reduce((acc, meter) => {
                            // 安全地获取并转换Used值
                            const used = meter && typeof meter.Used !== 'undefined' ? Number(meter.Used) : 0;
                            return acc + used;
                        }, 0),
                        subcategory: item.subcategory
                    };
                })
                .filter(item => item !== null)
                .sort((a, b) => b.value - a.value)
        } else {
            rankingChartData.value = [];
        }
    } catch (error) {
        handleError(error, '获取用途用水排名数据失败')
        rankingChartData.value = []
    } finally {
        rankingChartLoading.value = false
    }
}

// 监听时间变化
watch(() => rankingChartTime.value, getSubCategoryRankingData, { immediate: true })
</script>

<template>
    <div class="card-header">
        <span>{{ title }}</span>
        <CustomDateRadio @update:modelValue="rankingChartTime = $event"></CustomDateRadio>
    </div>
    <BaseRankingChart :title="title" :data="rankingChartData" :height="height" />
</template>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}
</style>